$(function(){
	changeBankCode();
	quickPay();
	comsumeSms();
});

function comsumeSms(){
	$('#comsumeSmsBtn').unbind('click');
	$('#comsumeSmsBtn').bind('click',function(){
		var reg = /^(13[0-9]|14[57]|15[0-35-9]|17[0135678]|18[0-9])[0-9]{8}$/;
		var payAmountReg=/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
		var digitReg = /^[0-9]+$/;
		var merKeyReg = /^[A-Za-z0-9]+$/;
		var phone = $('#phone').val();
		var payeeId = $('#payeeId').val();
		var creditCard = $('#payerAcc').val();
		var payAmount= $('#payAmount').val();
		var merKey = $('#merKey').val();
		if (!reg.test(phone)) {
			alertMsg('请输入正确的手机号码!');
			return;
		}
		if (!digitReg.test(payeeId)) {
			alertMsg('请输入正确的商户号!');
			return;
		}
		if(!digitReg.test(creditCard)){
			alertMsg('请输入正确的卡号!');
			return;
		}
		if(!payAmountReg.test(payAmount)){
			alertMsg('请输入正确的支付金额!');
			return;
		}
		if(!merKeyReg.test(merKey)){
			alertMsg('请输入正确的merKey');
			return;
		}
		var params = {
				phone:phone,
				payeeId:payeeId,
				creditCard:creditCard,
				payAmount:payAmount,
				merKey:merKey
		};
		var reqUrl = '../sms/sendComsumeSMS';
		$.ajax({
			url: reqUrl,
			type: 'POST',
			//同步执行
			async:false,
			data: params,
			dataType: 'json',
			success: function(data) {
				var result = data.result;
				var result = eval('('+ result +')');
				if(result != undefined){
					var smsCode = result.smsCode;
					var orderNo = result.orderNo;
					var channelCode = result.channelCode;
					if(orderNo != undefined){
						$('#orderNo').val(orderNo);
						if(smsCode != undefined){
							$('#smsCode').val(smsCode);
						}else{
							if(channelCode != undefined && channelCode == 'UNIONQUICKPAY'){
								$('#smsCode').val("111111");
							}else{
								alertMsg(result.execMsg);
							}
						}
					}else{
						alertMsg(result.execMsg);
					}
				}else{
					alertMsg("未知错误");
				}
			},
			error: function(data) {
				alertMsg("未知错误");
			}
		});
	});
}

function changeBankCode(){
	$('.cardType').unbind('click');
	$('.cardType').bind('click',function(){
		var self = $(this);
		var val = self.val();
		var array = new Array();
		if(val == 0){
			array.push('<option value="ICBC">工商银行</option>');
			array.push('<option value="ABC">农业银行</option>');
			array.push('<option value="CCB">建设银行</option>');
			array.push('<option value="BOC">中国银行</option>');
			array.push('<option value="CIB">兴业银行</option>');
			array.push('<option value="CEB">光大银行</option>');
			array.push('<option value="SPDB">浦发银行</option>');
			array.push('<option value="PINGAN">平安银行</option>');
			array.push('<option value="CMBCHINA">招商银行</option>');
			$('#_cvn2').hide();
			$('#_validDate').hide();
		}else{
			array.push('<option value="ICBC">工商银行</option>');
			array.push('<option value="ABC">农业银行</option>');
			array.push('<option value="BOC">中国银行</option>');
			array.push('<option value="CCB">建设银行</option>');
			array.push('<option value="POST">邮储银行</option>');
			array.push('<option value="ECITIC">中信银行</option>');
			array.push('<option value="CEB">光大银行</option>');
			array.push('<option value="HXB">华夏银行</option>');
			array.push('<option value="CMBC">民生银行</option>');
			array.push('<option value="CMBCHINA">招商银行</option>');
			array.push('<option value="CIB">兴业银行</option>');
			array.push('<option value="SPDB">浦发银行</option>');
			array.push('<option value="PINGAN">平安银行</option>');
			array.push('<option value="GDB">广发银行</option>');
			array.push('<option value="BCCB">北京银行</option>');
			array.push('<option value="SHB">上海银行</option>');
			$('#_cvn2').show();
			$('#_validDate').show();
		}
		$('#cardType').val(val);
		$('#bankCode').html('');
		$('#bankCode').html(array.join(''));
	  });
	}
	
	function quickPay(){
		$('#button').unbind('click');
		$('#button').bind('click',function(){
			var phoneReg = /^(13[0-9]|14[57]|15[0-35-9]|17[0135678]|18[0-9])[0-9]{8}$/;
			var payeeIdReg = /^[0-9]+$/;
			var merKeyReg = /^[A-Za-z0-9]+$/;
			var certNoReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
			var smsCodeReg = /^\d{6}$/;
			var cvn2Reg = /^\d{3}$/;
			var payAmountReg=/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
			var validDateReg = /^([1-9][0-9])(0?[13456789]|1[012])$/;
			var cvn2Reg = /^\d{3}$/;
			var cardType = $('#cardType').val();
			var bankCode = $('#bankCode').val();
			var phone = $('#phone').val();
			var payeeId = $('#payeeId').val();
			var payerAcc = $('#payerAcc').val();
			var validDate = $('#validDate').val();
			var cvn2 = $('#cvn2').val();
			var payerName = $('#payerName').val();
			var certNo = $('#certNo').val();
			var payAmount= $('#payAmount').val();
			var smsCode = $('#smsCode').val();
			var merKey = $('#merKey').val();
			var notifyUrl = $('#notifyUrl').val();
			var orderNo = $('#orderNo').val();
			var validDate = $('#validDate').val();
			if(!phoneReg.test(phone)){
				alertMsg('请输入正确的手机号码!');
				return;
			}
			if(!payeeIdReg.test(payeeId)){
				alertMsg('请输入正确的商户号码!');
				return;
			}
			if(!payeeIdReg.test(payerAcc)){
				alertMsg('请输入正确的卡号!');
			}
			if(cardType == 1){
				
				if (!validDateReg.test(validDate)) {
					alertMsg('请输入正确的有效日期!');
					return;
				}else{
					var currentTime = parseInt(moment().format('YYMM'));
					if(validDate < currentTime){
						alertMsg('有效日期小于当前时间!');
						return;
					}
				}
				if (!cvn2Reg.test(cvn2)) {
					alertMsg('请输入卡背后3位数字!');
					return;
				}
			}else{
				cvn2 = '';
			}
			if($.trim(payerName) == ''){
				alertMsg('真实姓名不能为空!');
				return;
			}
			if(!certNoReg.test(certNo)){
				alertMsg('请输入正确的身份证号!');
				return;
			}
			if(!payAmountReg.test(payAmount)){
				alertMsg('请输入正确的支付金额!');
				return;
			}
			if(!smsCodeReg.test(smsCode)){
				alertMsg('请输入正确的6位数验证码!');
				return;
			}
			if(!merKeyReg.test(merKey)){
				alertMsg('请输入正确的merKey!');
				return;
			}
			if($.trim(notifyUrl) == ''){
				alertMsg('请输入正确的回调链接URL!');
				return;
			}
			var params = {
					 cardType:cardType,
					 bankCode:bankCode,
					 phone:phone,
					 payeeId:payeeId,
					 payerAcc:payerAcc,
					 cvn2:cvn2,
					 validDate:validDate,
					 payerName:payerName,
					 certNo:certNo,
					 payAmount:payAmount,
					 smsCode:smsCode,
					 merKey:merKey,
					 orderNo:orderNo,
					 notifyUrl:notifyUrl
			};
			
			var reqUrl = '../quick/quickPay';
			$.ajax({
				url: reqUrl,
				type: 'POST',
				//同步执行
				async:false,
				data: params,
				dataType: 'json',
				success: function(data) {
					$('#result').text(JSON.stringify(data));
				},
				error: function(data) {
					alertMsg("未知错误");
				}
			});
			
		});
		
	}
	
	function alertMsg(msg){
		var params = {
		    container : {
			    content :msg
			  },
			autoClose : 1500
		};
		easyDialog.open(params);
	}
	
	function checkBankNo(t_bankno) {
		var bankno = $.trim(t_bankno);
		if (bankno == "") {
			alertMsg('请输入正确的银行卡号!');
			return false;
		}
		if (bankno.length < 16 || bankno.length > 19) {
			alertMsg('银行卡号长度必须在16到19之间!');
			return false;
		}
		var num = /^\d*$/; //全数字
		if (!num.exec(bankno)) {
			alertMsg('银行卡号必须全为数字!');
			return false;
		}
		//开头6位
		var strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
		if (strBin.indexOf(bankno.substring(0, 2)) == -1) {
			alertMsg('银行卡号开头6位不符合规范!');
			return false;
		}
		//Luhm校验（新）   
		if (!luhmCheck(bankno)){
			alertMsg('请输入正确的银行卡号!');
			return false;
		}
		return true;
	}

	//Luhm校验规则：16位银行卡号（19位通用）:
	//1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
	//2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
	//3.将加法和加上校验位能被 10 整除。
	function luhmCheck(bankno) {
		var lastNum = bankno.substr(bankno.length - 1, 1);//取出最后一位（与luhm进行比较）  
		var first15Num = bankno.substr(0, bankno.length - 1);//前15或18位  
		var newArr = new Array();
		for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组  
			newArr.push(first15Num.substr(i, 1));
		}
		var arrJiShu = new Array(); //奇数位*2的积 <9  
		var arrJiShu2 = new Array(); //奇数位*2的积 >9  
		var arrOuShu = new Array(); //偶数位数组  
		for (var j = 0; j < newArr.length; j++) {
			if ((j + 1) % 2 == 1) {//奇数位  
				if (parseInt(newArr[j]) * 2 < 9) {
					arrJiShu.push(parseInt(newArr[j]) * 2);
				} else {
					arrJiShu2.push(parseInt(newArr[j]) * 2);
				}
			} else {//偶数位 
				arrOuShu.push(newArr[j]);
			}
		}
		var jishu_child1 = new Array();//奇数位*2 >9 的分割之后的数组个位数  
		var jishu_child2 = new Array();//奇数位*2 >9 的分割之后的数组十位数  
		for (var h = 0; h < arrJiShu2.length; h++) {
			jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
			jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
		}
		var sumJiShu = 0; //奇数位*2 < 9 的数组之和  
		var sumOuShu = 0; //偶数位数组之和  
		var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和  
		var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和  
		var sumTotal = 0;
		for (var m = 0; m < arrJiShu.length; m++) {
			sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
		}
		for (var n = 0; n < arrOuShu.length; n++) {
			sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
		}
		for (var p = 0; p < jishu_child1.length; p++) {
			sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
			sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
		}
		//计算总和  
		sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu)
				+ parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

		//计算Luhm值  
		var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
		var luhm = 10 - k;
		if (lastNum == luhm) {
			return true;
		} else {
			return false;
		}
	}
